package com.example.filter;

import com.example.config.ProxyConfig;
import com.example.service.CommonHttpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Optional;
import java.util.stream.Collectors;

public class ProxyFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(ProxyFilter.class);

    private final CommonHttpService commonHttpService;
    private final ProxyConfig proxyConfig;

    public ProxyFilter(CommonHttpService commonHttpService, ProxyConfig proxyConfig) {
        this.commonHttpService = commonHttpService;
        this.proxyConfig = proxyConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 根据请求路径匹配配置
        Optional<ProxyConfig.ProxyMapping> proxyMapping = proxyConfig.getMappings().stream()
                .filter(mapping -> request.getRequestURI().startsWith(mapping.getPath()))
                .findFirst();

        if (proxyMapping.isPresent()) {
            ProxyConfig.ProxyMapping mapping = proxyMapping.get();
            String targetUrl = mapping.getUrl();

            try {
                log.info("转发请求 [{}] 到目标地址 [{}]", request.getRequestURI(), targetUrl);

                // 获取请求体
                String body = extractBody(request);

                // 转发请求并获取响应
                ResponseEntity<String> targetResponse = commonHttpService.forwardRequest(body, targetUrl);

                // 将目标服务的响应写回到客户端
                response.setStatus(targetResponse.getStatusCodeValue());
                // 设置响应的字符编码和内容类型
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=UTF-8");
                // 写入响应体（如果不为 null）
                if (targetResponse.getBody() != null) {
                    response.getWriter().write(targetResponse.getBody());
                }
            } catch (Exception e) {
                log.error("转发过程中发生异常: {}", e.getMessage(), e);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("转发失败: " + e.getMessage());
            }
        } else {
            // 如果未匹配到转发规则，继续正常过滤链
            chain.doFilter(servletRequest, servletResponse);
        }
    }

    private String extractBody(HttpServletRequest request) throws IOException {
        return new BufferedReader(new InputStreamReader(request.getInputStream()))
                .lines()
                .collect(Collectors.joining(System.lineSeparator()));
    }
}
